<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script>
    var Promise=function(){
        this.isPromise = true;
        this.queue=[]
    }

    Promise.prototype.then=function(resolve,reject){
        var handler={};
        if(typeof resolve ==='function'){
            handler.resolve = resolve;
        }
        if(typeof reject==='function'){
            handler.reject=reject;
        }
        this.queue.push(handler);
        return this;
    }

    var Deferred = function (){
        this.promise=new Promise();
    }

    Deferred.prototype.resolve=function(data){
        var handler;
        while(handler=this.promise.queue.shift()){
            if(handler&&handler.resolve){
                var ret=handler.resolve(data);
                if(ret && ret.isPromise){
                    ret.quene=this.promise.quene;
                    this.promise=ret;
                    return;
                }
            }
        }
    }


    Deferred.prototype.reject=function(err){
        var handler;
        while(handler=this.promise.queue.shift()){
            if(handler&&handler.reject){
                var ret=handler.reject(err);
                if(ret&&ret.isPromise){
                    ret.queue=this.promise.queue;
                    this.promise=ret;
                    return;
                }
            }
        }
    }

    Deferred.prototype.makeNodeResolver= function () {
        var _this=this;
        return function(err,res){
            if(err) return _this.reject(err);
            _this.resolve(res);
        }
    }

    function fs_readFile(file,code,cb){
        cb(null,'readfile'+file+code);
    }
    function fs_readJSON(file,code,cb){
        cb(null,'readJSON'+file+code);
    }

    var readFile = function (file){
        var deferred=new Deferred();
        fs_readFile(file,'utf-8',deferred.makeNodeResolver());
        return deferred.promise;
    }
    var readJSON = function (file) {
        var deferred=new Deferred();
        fs_readFile(file,'utf-8',function(err,file){
            if(err) return deferred.reject(err)
            deferred.resolve('JSON parse'+file)
        })
    }

    readFile('hello.txt').then(function(file){
        console.log(file)
        return readJSON(file);
    }).then(function(data){
        console.log(data);
    })


</script>
</body>
</html>






